package com.witframework.util;



/*
 * justify a string, here only left justification is implemented
 */
public class FormatLine {
	public static String justifyLeft(int width, String st) {
		StringBuffer buf = new StringBuffer(st);
		int lastspace = -1;
		int linestart = 0;
		int i = 0;

		while (i < buf.length()) {
			if (buf.charAt(i) == ' ')
				lastspace = i;
			if (buf.charAt(i) == '\n') {
				lastspace = -1;
				linestart = i + 1;
			}
			if (i > linestart + width - 1) {
				if (lastspace != -1) {
					buf.setCharAt(lastspace, '\n');
					linestart = lastspace + 1;
					lastspace = -1;
				} else {
					buf.insert(i, '\n');
					linestart = i + 1;
				}
			}
			i++;
		}
		return buf.toString();
	}

	public static void main(String arg[]) {
		String formatted_string;
		String original_string = "01234567890123456789你好你好的速度多少速度速度速度uya呀挥洒的   01234567890 0123   4565789 ";

		formatted_string = FormatLine.justifyLeft(25, original_string);

		System.out.println("---------");
		System.out.println(original_string);
		System.out.println("---------");
		System.out.println(formatted_string);
	}
}
